<?php

namespace app\admin\controller\facrm\customer;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 *联系人
 */
class Contacts extends Backend
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'customer_id,name,mobile,telephone';
    protected $childrenAdminIds = [];
    protected $addon_config = array();

    public function _initialize()
    {
        parent::_initialize();
        $this->addon_config = get_addon_config('facrm');
        $this->model = model('\app\admin\model\facrm\customer\Contacts');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 联系人列表
     */
    public function index($customer_id = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'contacts')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_w = [];
            $filter_w['owner_user_id'] = $this->auth->id;
            if (isset($filter['scene_id'])) {
                if (!isset($scene_list[$filter['scene_id']])) {
                    $this->error(__("您没有权限"));
                }

                switch ($filter['scene_id']) {
                    case 4:
                        //全部 超级管理员不做限制
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                        if ($this->childrenAdminIds)
                            $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    case 5:
                        //我的
                        $filter_w['owner_user_id'] = $this->auth->id;
                        break;
                    case 6:
                        //下属
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                        if ($this->childrenAdminIds)
                            $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    default://其它的还做TODO
                        $filter_w['owner_user_id'] = $this->auth->id;

                }

                unset($filter['scene_id']);
                $this->request->get(['filter' => json_encode($filter)]);
            }
            if ($customer_id) {
                $filter_w['customer_id'] = $customer_id;
                //判断是否有该客户的权限
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $custom=$this->request->request('custom/a');
                $this->request->request(['custom' => array_merge($custom,$filter_w)]);
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //$customer_id ? $this->model->where('customer_id', $customer_id) : '';
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'owner_user' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ])
                ->order($sort, $order)->fetchSql(false)
                ->count();
            //$customer_id ? $this->model->where('customer_id', $customer_id) : '';
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'owner_user' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            if ($this->addon_config['show_contacts'] != 1) {
                $pattern = '/(\d{3})(\d{4})(\d{4})/i';
                $replacement = '$1****$3';
                //为了安全隐藏手机和电话
                foreach ($list as $row) {
                    $row->mobile = $row->mobile ? preg_replace($pattern, $replacement, $row->mobile) : '';
                    $row->telephone = $row->telephone ? preg_replace($pattern, $replacement, $row->telephone) : '';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        /**
         * 自定义字段
         */

        /**
         * 自定义字段
         */
        $fields = \app\admin\model\facrm\Fields::getCustomFieldsTable('customer_contacts', [], 'isfilter=1 or islist=1');
        if ($fields) {
            $this->assignconfig('fields', json_encode($fields));
        }
        $this->view->assign("scene_list", $scene_list);
        return $this->view->fetch();
    }

    /**
     * 添加联系人
     * @return mixed
     */
    public function add($customer_id = null)
    {
        $customer = model('\app\admin\model\facrm\Customer');
        $row = $customer->get($customer_id);

        if (!$row)
            $this->error(__('No Results were found'));

        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCustomerAuth($customer_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['next_time'] = $params['next_time'] ? strtotime($params['next_time']) : 0;

            if (empty($params['birthday'])) unset($params['birthday']);
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $params = array_merge($params, [
                        'create_user_id' => $this->auth->id,
                        'owner_user_id' => $row->owner_user_id,
                        'customer_id' => $row->id,
                        'types' => 'customer',
                    ]);
                    $result = $this->model->add($params);
                    Db::commit();
                } catch (ValidateException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError() ? __($this->model->getError()) : __('添加失败'));
                }
            }
            $this->error(__('参数不能为空', ''));

        } else {
            $this->view->assign("row", $row);
        }

        return parent::add();
    }

    /**
     * 修改联系人
     * @param null $ids
     * @return mixed
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCustomerAuth($row->customer_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['next_time'] = $params['next_time'] ? strtotime($params['next_time']) : '0';
            $params = array_merge($params, [
                'next_time' => $params['next_time'],
                'birthday' => !empty($params['birthday']) ? $params['birthday'] : NULL,
            ]);
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->edit($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError() ? __($row->getError()) : __('修改失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));

        }
        $this->assignconfig('contacts_id', $ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
